package cn.cjxy.demo.controller;

import cn.cjxy.demo.domain.User;
import cn.cjxy.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private HttpSession httpSession;
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param user
     * @param checkCode
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, String checkCode, Model model){
        //从session中取得验证码
        String sessionCode = (String) httpSession.getAttribute("sessionCode");
        //对比验证码
        if(!checkCode.equalsIgnoreCase(sessionCode)){//不相等回到登录页
            //提示验证码错误
            model.addAttribute("error","验证码错误！请重新输入！");
            return "login";
        }
        //验证码，比对用户名和密码
        //将用户名和密码传回数据库中查询用户
        User dbuser=userService.findByUsername(user.getUsername());
        if(dbuser == null ||!dbuser.getPassword().equals(user.getPassword())){//如果没查出来
            model.addAttribute("error","用户名或密码错误!");
            //回到登录页
            return "login";
        }

        //重定向到/user/list请求
        return "redirect:/user/list";
    }

    /**
     * 查询用户列表
     * 返回数据到list.html页面去
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(String username,String address,Model model){
        //查出所有用户信息
        List<User> users = userService.findAll(username,address);
        //存入model
        model.addAttribute("userList",users);
        //跳到list.html页面
        return "list";
    }

    /**
     * 用户信息回显
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/userDetail")
    public String userDetail(Integer id, Model model){
        //根据传递的id查出用户对象，将用户对象回显
        User user=userService.findById(id);
        model.addAttribute("user",user);
        //跳转到修改页面
        return "update";
    }
    /**
     * 执行修改操作，跳转到首页再查一遍
     */
    @RequestMapping("/update")
    public String update(User user){
        userService.update(user);
        //重定向到/list请求
        return "redirect:/user/list";
    }

}
